import InterfaceExt, Xml, os
from time import strptime, strftime

def Recover(path, list=[], time='Now'):
    """ Interface used to recover a file or a set of files from a specific date """
    
    if len(list)==0 and time=='Now':
        listAll = Xml.retrieveAllXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml')
        for elements in listAll:
            name=elements.split('_')
            timeval=name[-1].split('.')
            InterfaceExt.xdeltaRecover(timeval[0], name[0], path)
            aclTime=getClosestAclDate(name[0], timeval[0])
            if aclTime != '01-01-1901@01h01m01s':
                InterfaceExt.setAclRestore(aclTime, name[0], path)
    else:
        if len(list)!=0 and time=='Now':
            listAll = Xml.retrieveAllXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml')
            for elements in listAll:
                name=elements.split('_')
                timeval=name[-1].split('.')
                if name[0] in list:
                    InterfaceExt.xdeltaRecover(timeval[0], name[0], path)
                    aclTime=getClosestAclDate(name[0], timeval[0])
                    if aclTime != '01-01-1901@01h01m01s':
                        InterfaceExt.setAclRestore(aclTime, name[0], path)
        else:
            for elements in list:
                    InterfaceExt.xdeltaRecover(time, elements, path)
                    aclTime=getClosestAclDate(elements, time)
                    if aclTime != '01-01-1901@01h01m01s':
                        InterfaceExt.setAclRestore(aclTime, elements, path)
                
def getClosestAclDate(filename, date, type='acl'):
    """ Return the closest data for a given date and filename (in case they don't have the same timing (i.e. not matchin same seconds or minutes)"""
    
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    dategiven = strptime(date, "%d-%m-%Y@%Hh%Mm%Ss")
    result='NULL'
    temp = strptime('01-01-1901@01h01m01s', "%d-%m-%Y@%Hh%Mm%Ss")
    for elements in listBackup:
            value = elements.split('.')
            dateCheck = elements.split('_')
            if (value[-1]==type) and (dateCheck[0]==filename) :
                dateval = dateCheck[-1].split('.')
                a = strptime(dateval[0], "%d-%m-%Y@%Hh%Mm%Ss")
                if (a > temp) and (a < dategiven):
                    temp=a
    result = strftime("%d-%m-%Y@%Hh%Mm%Ss", temp)
    return result
                
def getTimesToRecover(filename):
    """ Return a list containing the different available backups to recover from/for a given file """
    
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    #print listBackup
    listoftimes=[]
    for elements in listBackup:
        value = elements.split('.')
        if value[-1]=='xdelta':
            decompose=elements.split('_')
            if decompose[0]==filename:
                x=decompose[-1].split('.')
                listoftimes.append(x[0])
    return listoftimes
        
def AddToBackup(list):
    """ Interface to add new elements to backup """
    
    #print li
    dir = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(dir[0])
    bool=False
    listOfDuplicates=[]
    for element in list:
        basename = os.path.basename(element)
        if basename in listBackup:
            bool=True
            listOfDuplicates.append(element)
    if bool==False:
        Xml.addToXml('C:\\Program Files\\EasyBackupTool\\backupFile.xml', list)
        InterfaceExt.initialisationBackup(list)
    else:
        print 'The following items have an item existing in the backup registry already. To prevent from deleting other file , please take care of changing those names by new others'
        print listOfDuplicates
    
def checkTreshold(treshold):
    
    result = 'NULL'
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    send = []
    result=os.popen('dir C:\ ').read()
    truc = result.split('\n')
    res= truc[-3:]
    res.remove('')
    mem = res[0].split(' ')
    mem1 = res[1].split(' ')
    mem_used = mem[-2]
    mem_free = mem1[-3]
    mem_used = mem_used.replace(',','')
    mem_free = mem_free.replace(',','')
    if mem_free[:4]<treshold:
        result = 'WARNING : DISK IS GETTING FULL, PLEASE TAKE APPROPRIATE MEASURES TO FREE DISK SPACE'
    return result
    
if __name__ == "__main__":
    list = ['C:\\Transmac7.5.zip']
    AddToBackup(list)
    #checkTreshold('2900')
    #checkTreshold('1499')
   # a= strptime("11-07-2008@16h04m21s", "%d-%m-%Y@%Hh%Mm%Ss")
   # b= strptime("11-07-2008@16h04m55s", "%d-%m-%Y@%Hh%Mm%Ss")
    #getTimesToRecover('img.jpg')
    #if a < b:
       # print 'a < b'
    #else :
       # print 'b < a'
    #print getClosestAclDate('img.JPG', '11-07-2008@16h04m21s')
    
    
    